<?php
/**
 * 派单管理
 * Created by PhpStorm.
 * User: 北山道人
 * Date: 2018/6/29
 * Time: 17:44
 */
namespace app\admin\controller;
use app\repository\PushMess;
use app\repository\Repository;
use think\Request;

class Dispatch extends Common
{
    /**
     * 派单列表页面
     * @return mixed
     */
    public function listUI(){
        return $this->fetch('list');
    }

    /**
     * 平台工程师接单列表
     * @return mixed
     */
    public function meListUI(){
        return $this->fetch('melist');
    }

    /**
     * 历史派单列表页面
     * @return mixed
     */
    public function hisUI(){
        return $this->fetch('his');
    }

    /**
     * 创建派单任务页面
     * @return mixed
     */
    public function addUI()
    {
        return $this->fetch('add');
    }

    /**
     * 详情页面
     * @return mixed
     */
    public function disInfo(){
        $info = db('dispatch')->alias('w')
            ->where('w.id',input('id'))
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->join('admin reg','reg.admin_id=w.reg_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username','a.name','reg.username as reg_username','reg.name as reg_name'])
            ->find();

        $rows = db('dispatch_sheets')->alias('ds')
            ->where('ds.dispatch_id',input('id'))
            ->join('admin ad','ds.admin_id=ad.admin_id','left')
            ->field(['ds.*','ad.name as admin_name'])->order('ds.id','desc')->select();
        foreach ($rows as &$v){
            $v['list'] = db('dispatch_flow')->alias('df')
                ->where('df.sheet_id',$v['id'])
                ->join('admin ad','ad.admin_id=df.admin_id','left')
                ->field(['df.*','ad.name as admin_name'])->order('id','desc')->select();
        }

        $info['track'] = $rows;

        return $this->fetch('disInfo',['info'=>json_encode($info)]);
    }

    /**
     * 派单任务列表
     * @param Request $request
     * @return array
     */
    public function queryPage(Request $request){
        $input = $request->param();

        $rows = db('dispatch')->alias('w')->order('w.id desc')->where(function ($query)use($input){

            /*if(session('gid') != 1 && session('gid') != 7)
                $query->where('w.engin_id',session('aid'));*/

            if(session('gid')==9){
                $query->where('w.reg_id',session('aid'));
            }
            if(session('gid')==6){
                $query->where('w.admin_id',session('aid'));
            }

            if(isset($input['is_me'])){
                $query->where('w.is_me',$input['is_me']);
            }

            if(!empty($input['id'])){
                $query->where('w.id',$input['id']);
            }

            if(!empty($input['fault_id'])){
                $query->where('w.fault_id',$input['fault_id']);
            }
            if(!empty($input['state_id'])){
                $sis = explode(',',$input['state_id']);
                $query->where('w.state_id','in',$sis);
            }
            if(!empty($input['tel'])){
                $query->where('w.tel',$input['tel']);
            }

            if(!empty($input['key'])){
                /*$query->where('w.title','LIKE','%'.$input['key'].'%');
                $query->whereOr('ws.number',$input['key']);
                $query->whereOr('w.tel',$input['key']);*/
                $query->where('w.title|ws.number|w.tel|w.number','LIKE','%'.$input['key'].'%');
            }

            if(!empty($input['admin_id'])){
                $query->where('w.admin_id',$input['admin_id']);
            }

            if(!empty($input['reg_id'])){
                $query->whereOr('w.reg_id',$input['reg_id']);
        }
        })
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->join('admin reg','reg.admin_id=w.reg_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username','a.name','reg.username as reg_username','reg.name as reg_name'])
            ->paginate($input['limit'])
            ->toArray();
        return ['code'=>0,'msg'=>'获取成功!','data'=>$rows['data'],'count'=>$rows['total'],'rel'=>1];
    }

    /**
     *
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function queryDis(Request $request){
        $input = $request->param();
        $input['dis'] = [0];
        $at = db('dispatch_at')->where('admin_id',session('aid'))->select();
        foreach ($at as $v){
            $input['dis'][] = $v['dispatch_id'];
        }
        $rows = db('dispatch')->alias('w')->order('w.id desc')->where(function ($query)use($input){

            if(isset($input['is_me'])){
                $query->where('w.is_me',$input['is_me']);
            }

            if(!empty($input['id'])){
                $query->where('w.id',$input['id']);
            }

            if(!empty($input['dis'])){
                $query->where('w.id','in',$input['dis']);
            }

            if(!empty($input['fault_id'])){
                $query->where('w.fault_id',$input['fault_id']);
            }
            if(!empty($input['state_id'])){
                $sis = explode(',',$input['state_id']);
                $query->where('w.state_id','in',$sis);
            }
            if(!empty($input['tel'])){
                $query->where('w.tel',$input['tel']);
            }

            if(!empty($input['key'])){
                $query->where('w.title|ws.number|w.tel|w.number','LIKE','%'.$input['key'].'%');
            }

            if(!empty($input['reg_id'])){
                $query->whereOr('w.reg_id',$input['reg_id']);
            }
        })
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->join('admin reg','reg.admin_id=w.reg_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username','reg.username as reg_username','reg.name as reg_name'])
            ->paginate($input['limit'])
            ->toArray();
        foreach ($rows['data'] as &$v){
            $v['is_conf'] = null;
            foreach ($at as $vt){
                if($v['id']==$vt['dispatch_id']){
                    $v['is_conf'] = $vt['is_conf'];
                    $v['cause'] = $vt['cause'];
                    $v['is_lead'] = $vt['is_lead'];
                }
            }
        }
        return ['code'=>0,'msg'=>'获取成功!','data'=>$rows['data'],'count'=>$rows['total'],'rel'=>1];
    }


    /**
     * 创建派单任务
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function add(Request $request){
        $input = $request->param();

        $input['state_id'] = 20;

        $msg = $this->validate($input,'app\admin\validate\Dispatch');
        if($msg!='true'){
            return ['code'=>0,'msg'=>$msg];
        }
        if(session('gid')=='5')
            $input['engin_id'] = session('aid');

        $input['create_id'] = session('aid');

        if(session('gid')=='9'){
            $input['reg_id'] = session('aid');
            $input['state_id'] = 21;
        }

        $input['number'] = 'D'.date("YmdH",time()).rand(101,999);

        $did = db('dispatch')->insertGetId($input);

        if($did && !empty($input['works_id'])){
            db('works')->where('id',$input['works_id'])->update(['state_id'=>12]);
        }
        if($did)
            return ['code'=>1,'msg'=>'创建成功'];
        return ['code'=>0,'msg'=>'创建失败'];
    }

    /**
     * 派单给第三方
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function dis(Request $request){
        $id = $request->param('id');
        $aid = $request->param('aid');
        if(empty($id)) return ['code'=>0,'msg'=>'id参数错误'];
        if(empty($aid)) return ['code'=>0,'msg'=>'请选择第三方'];
        $row = db('dispatch')->where('id',$id)->update(['admin_id'=>$aid,'state_id'=>22]);
        if($row)
            return ['code'=>1,'msg'=>'派单成功'];
        return ['code'=>0,'msg'=>'派单失败'];
    }

    //派单给=区域经理
    public function disToEngin(Request $request){
        $id = $request->param('id');
        $aid = $request->param('aid');
        if(empty($id)) return ['code'=>0,'msg'=>'id参数错误'];
        if(!isset($aid)) return ['code'=>0,'msg'=>'请选择区域经理'];
        if($aid==0){
            $row = db('dispatch')->where('id',$id)->update(['is_pub'=>1,'state_id'=>22,'is_select'=>0]);
            if($row){

                $info = db('dispatch')->where('id',$id)->find();
                $ulist = db('admin')->where(['group_id'=>9])->select();
                $data = [
                    'first'=>[
                        'value'=>"您好！有新工单已发布！", 'color'=>'#000'
                    ],
                    "keyword1"=>["value"=>$info['number'], "color"=>"#173177"],
                    "keyword2"=>["value"=>date('Y-m-d H:i:s'), "color"=>"#173177"],
                    "remark"=>["value"=>"点击查看详情！", "color"=>"#173177"],
                ];
                $openid = [];
                foreach ($ulist as $v){
                    $openid[] = $v['admin_id'];
                }
                $openid = array_filter($openid);
                PushMess::sendTemplate($openid,$data,'NBeGDf2utQuF3NOMUJC1-uFZEINpeZu6PaasF_4_22A',getUrl().url('wchat/Receipt/getDisUI').'?id='.$id);

                return ['code'=>1,'msg'=>'派单成功'];
            }
        }else{
            $row = db('dispatch')->where('id',$id)->update(['reg_id'=>$aid,'state_id'=>22,'is_select'=>1]);
            if($row){

                /*\app\repository\Dispatch::addTeam($id,$aid,'wchat/Enginme/getUI');
                \app\repository\Dispatch::lead($id,$aid);*/
                //发送推送消息
                $info = db('dispatch')->where('id',$id)->find();

                $data = [
                    'first'=>[
                        'value'=>"您好！该工单分配给您，请你尽快处理！", 'color'=>'#000'
                    ],
                    "keyword1"=>["value"=>$info['number'], "color"=>"#173177"],
                    "keyword2"=>["value"=>date('Y-m-d H:i:s'), "color"=>"#173177"],
                    "remark"=>["value"=>"点击查看详情", "color"=>"#173177"],
                ];

                PushMess::sendTemplate($aid,$data,'NBeGDf2utQuF3NOMUJC1-uFZEINpeZu6PaasF_4_22A',getUrl().url('wchat/Manager/getDisUI').'?id='.$id);

                return ['code'=>1,'msg'=>'派单成功'];
            }
        }
        return ['code'=>0,'msg'=>'派单失败'];
    }

    /**
     * 工程师接单-自己派单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function confMe(Request $request){

        $id = $request->param('id');
        if(empty($id)) return ['code'=>0,'msg'=>'id参数错误'];
        $row = db('dispatch')->where('id',$id)->where('admin_id',session('aid'))->update(['state_id'=>25]);
        if($row){

            db('dispatch_at')->where(['dispatch_id'=>$id,'admin_id'=>session('aid')])->update(['is_conf'=>1]);
            $info = db('admin')->where('admin_id',session('aid'))->find();
            $input = [];
            $input['icon']        = "/public/static/wx/img/progress-list/t1.png";
            $input['admin_id']    = session('aid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."已接单";
            $input['step']        = 1;
            db('dispatch_flow')->insert($input);
            $input['icon']        = "/public/static/wx/img/progress-list/t2.png";
            $input['admin_id']    = session('aid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."已组建团队";
            $input['step']        = 2;
            db('dispatch_flow')->insert($input);

            return ['code'=>1,'msg'=>'接单成功'];
        }
        return ['code'=>0,'msg'=>'接单失败'];
    }

    /**
     * 第三方接单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function receipt(Request $request)
    {
        $id = $request->param('id');

        $row = db('dispatch')->where('id',$id)->update(['state_id'=>21]);

        if($row){
            $info = db('admin')->where('admin_id',session('aid'))->find();
            $input = [];
            $input['icon']        = "/public/static/wx/img/progress-list/t1.png";
            $input['admin_id']    = session('aid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."已接单";
            $input['step']        = 1;
            db('dispatch_flow')->insert($input);
            $input['icon']        = "/public/static/wx/img/progress-list/t2.png";
            $input['admin_id']    = session('aid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."已组建团队";
            $input['step']        = 2;
            db('dispatch_flow')->insert($input);

            return ['code'=>1,'msg'=>'接单成功'];
        }
        return ['code'=>0,'msg'=>'接单失败'];
    }

    /**
     * 第三方拒单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function refusal(Request $request)
    {
        $id = $request->param('id');
        $val = $request->param('val');
        $row = db('dispatch')->where('id',$id)->update(['state_id'=>23,'reason'=>$val]);
        if($row)
            return ['code'=>1,'msg'=>'信息发送成功'];
        return ['code'=>0,'msg'=>'信息发送失败'];
    }

    /**
     * 组长拒单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function meetre(Request $request){
        $id = $request->param('id');
        $val = $request->param('val');
        $row = db('dispatch_at')->where(['dispatch_id'=>$id,'admin_id'=>session('aid')])->update(['is_conf'=>2,'cause'=>$val]);
        if($row)
            return ['code'=>1,'msg'=>'信息发送成功'];
        return ['code'=>0,'msg'=>'信息发送失败'];
    }

    /**
     * 组员接单
     */
    public function meeteam(Request $request){
        $id = $request->param('id');
        $row = db('dispatch_at')->where(['dispatch_id'=>$id,'admin_id'=>session('aid')])->update(['is_conf'=>1]);
        if($row)
            return ['code'=>1,'msg'=>'信息发送成功'];
        return ['code'=>0,'msg'=>'信息发送失败'];
    }

    /**
     * 结束任务单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function comp(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        $row = db('dispatch')->where('id',$did)->update(['is_comp'=>1]);
        if($row)
            return ['code'=>1,'msg'=>'操作成功'];
        return ['code'=>0,'msg'=>'操作失败'];
    }

    /**
     * 创建团队
     * @param Request $request
     * @return array
     */
    public function team(Request $request){
        $did = $request->param('dis_id');
        $aids = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aids)) return ['code'=>0,'msg'=>'aid参数错误'];
        return \app\repository\Dispatch::team($did,$aids);
    }

    /**
     * 添加团队人员
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function addTeam(Request $request){
        $did = $request->param('dis_id');
        $aids = $request->param('aid');
        $isg = $request->param('is_group');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aids)) return ['code'=>0,'msg'=>'aid参数错误'];
        $rule = \app\repository\Dispatch::addTeam($did,$aids);
        if($rule['code']==1){
            $aids = explode(',',$aids);
            $aids = array_filter($aids);
            if(!empty($isg)&&$isg==1)
            {
                foreach ($aids as $v){
                    db('dispatch_at')->where(['dispatch_id'=>$did,'admin_id'=>$v])->update(['is_lead'=>1]);
                }
            }else{
                foreach ($aids as $v){
                    db('dispatch_at')->where(['dispatch_id'=>$did,'admin_id'=>$v])->update(['apid'=>session('aid')]);
                }
            }
        }
        return $rule;
    }

    /**
     * 移除团队人员
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove(Request $request){
        $did = $request->param('dis_id');
        $aid = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aid)) return ['code'=>0,'msg'=>'aid参数错误'];
        return \app\repository\Dispatch::remove($did,$aid);
    }

    /**
     * 设置领队人
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function lead(Request $request){
        $did = $request->param('did');
        $aid = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'did参数错误'];
        if(empty($aid)) return ['code'=>0,'msg'=>'aid参数错误'];
        return \app\repository\Dispatch::lead($did,$aid);
    }

    /**
     * 任务团队
     * @param Request $request
     * @return array
     */
    public function teamList(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        $rows = db('dispatch_at')->alias('da')
            ->where('da.dispatch_id',$did)
            ->join('admin a','a.admin_id=da.admin_id','left')
            ->join('jobs j','j.id=a.jobs_id','left')
            ->field(['a.*','j.title as jobs_title','da.is_lead','da.is_conf','da.cause','da.apid','da.add_time'])
            ->select();
        $rows = Repository::treeData($rows,0,'apid','admin_id');
        return ['code'=>1,'data'=>$rows];
    }


    /**
     * 跟踪列表
     * @param Request $request
     */
    public function track(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];

        $rows = db('dispatch_sheets')->alias('ds')
            ->where('ds.dispatch_id',$did)
            ->join('admin ad','ds.admin_id=ad.admin_id','left')
            ->field(['ds.*','ad.name as admin_name'])->order('ds.id','desc')->select();
        foreach ($rows as &$v){
            $v['list'] = db('dispatch_flow')->alias('df')
                ->where('df.sheet_id',$v['id'])
                ->join('admin ad','ad.admin_id=df.admin_id','left')
                ->field(['df.*','ad.name as admin_name'])->order('id','desc')->select();
        }
        return ['code'=>1,'data'=>$rows];
    }

    /*******************************************************************************/

    public function trackList(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];


    }
    /*******************************************************************************/

    /**
     * 派单给组长
     */
    public function toGroup(){
        $ids = \request()->param('ids');//组长ids
        $did = \request()->param('dis_id');//任务id
        if(empty($ids)) return ['code'=>0,'msg'=>'ids参数错误'];
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        $ids = explode(',',$ids);
        $ids = array_filter($ids);
        $ins = [];
        foreach ($ids as $v){
            $ins[] = [
                'dispatch_id'=>$did,
                'admin_id'=>$v,
                'is_lead'=>1
            ];
        }
        $row = db('dispatch_at')->insertAll($ins);
        if($row){
            db('dispatch')->where('id',$did)->update(['is_team'=>1,'state_id'=>25]);
            return ['code'=>1,'msg'=>'操作成功'];
        }

        return ['code'=>0,'msg'=>'操作失败'];
    }

    /**
     * 删除工单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del(Request $request){
        $did = $request->param('id');
        db('dispatch')->where('id',$did)->delete();
        db('dispatch_at')->where('dispatch_id',$did)->delete();
        db('dispatch_flow')->where('dispatch_id',$did)->delete();
        db('dispatch_tools')->where('dispatch_id',$did)->delete();
        db('dispatch_eval')->where('dispatch_id',$did)->delete();
        return ['code'=>1,'msg'=>'操作完成'];
    }


    /**
     * 组长接单
     * @param Request $request
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function meeten(Request $request){
        $id = $request->param('id');
        $row = db('dispatch')->where('id',$id)->update(['state_id'=>25]);
        if($row){
            db('dispatch_at')->where(['dispatch_id'=>$id,'admin_id'=>session('aid')])->update(['is_conf'=>1]);

            $info = db('admin')->where('admin_id',session('aid'))->find();
            $input = [];
            $input['icon']        = "/public/static/wx/img/progress-list/t1.png";
            $input['admin_id']    = session('aid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."已接单";
            $input['step']        = 1;
            db('dispatch_flow')->insert($input);
            $input['icon']        = "/public/static/wx/img/progress-list/t2.png";
            $input['admin_id']    = session('aid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."已组建团队";
            $input['step']        = 2;
            db('dispatch_flow')->insert($input);

            return ['code'=>1,'msg'=>'接单成功'];
        }
        return ['code'=>0,'msg'=>'接单失败'];
    }

}